package cn.tedu.weibo.controller;

import cn.tedu.weibo.commom.response.JsonResult;
import cn.tedu.weibo.config.CaffeineConfig;
import cn.tedu.weibo.pojo.dto.WeiboDTO;
import cn.tedu.weibo.pojo.vo.WeiboDetailVO;
import cn.tedu.weibo.pojo.vo.WeiboIndexVO;
import cn.tedu.weibo.service.IWeiboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/v1/weibos")
public class WeiboController {
    @Autowired
    IWeiboService weiboService;
    @Resource
    CaffeineConfig caffeineConfig;
    @PostMapping("add-new")
    public JsonResult addNew(@RequestBody WeiboDTO weiboDTO){
        System.out.println("weiboDTO"+weiboDTO);
        weiboService.addNew(weiboDTO);
        return JsonResult.ok();
    }
    @GetMapping("index")
    public JsonResult index(){
       /* List<WeiboIndexVO> weiboIndexVO=(List<WeiboIndexVO>) caffeineConfig.get(null);
        if (weiboIndexVO!=null){
            System.out.println("从weiboIndexVO缓存中获取数据");
            return JsonResult.ok(weiboIndexVO);
        }
        //从数据库中获取缓存
        weiboIndexVO=weiboService.listForIndex();
        //就数据放进缓存中
        System.out.println("从数据库中获取的信息");
        caffeineConfig.put(null,weiboIndexVO);

        return JsonResult.ok(weiboIndexVO);*/
        return JsonResult.ok();
    }
    @GetMapping("{id}")
    public JsonResult datailByid(@PathVariable Long id){
        // 尝试从缓存中获取数据
        WeiboDetailVO weiboDetailVO=(WeiboDetailVO) caffeineConfig.get(id);
        if (weiboDetailVO!=null){
            System.out.println("从weiboDetailVO缓存中获取数据");
            return JsonResult.ok(weiboDetailVO);
        }
        // 没有缓存，从数据库获取数据
        weiboDetailVO=weiboService.detailById(id);
        // 将数据放入缓存
        System.out.println("从数据库的获取的信息");
        caffeineConfig.put(id,weiboDetailVO);

        return JsonResult.ok(weiboDetailVO);
    }
}
